package com.itheima.async;

import java.util.Random;
import java.util.concurrent.*;

/**
 * @program: itheima-jdk8
 * @description:
 * @author: zhanghz001
 * @create: 2021-01-08 09:40
 **/
public class FutureAsyncDemo1 {
    
    static ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(
            3, 3, 60L
            , TimeUnit.MILLISECONDS, new ArrayBlockingQueue<Runnable>(1)
    );
    
    public static void main(String[] args) {
        long start = System.currentTimeMillis();
        
        //
        Future<Integer> submit1 = poolExecutor.submit(new CallableTask());
        Future<Integer> submit2 = poolExecutor.submit(new CallableTask());
        Future<Integer> submit3 = poolExecutor.submit(new CallableTask());
        System.out.println("做其他事情");
        Integer a = 0;
        Integer b = 0;
        Integer c = 0;
        try {
            a = submit1.get();
        } catch (Exception e) {
            submit1.cancel(true);
            e.printStackTrace();
        }
        try {
            b = submit2.get();
        } catch (Exception e) {
            submit2.cancel(true);
            e.printStackTrace();
        }
        try {
            c = submit3.get();
        } catch (Exception e) {
            submit3.cancel(true);
            e.printStackTrace();
        }
        //
        poolExecutor.shutdown();
        System.out.println(System.currentTimeMillis() - start);
        System.out.println(a + b + c);
    }
}

class CallableTask implements Callable<Integer> {
    static Random random = new Random();
    
    @Override
    public Integer call() throws Exception {
        doSomething();
        System.out.println(Thread.currentThread().getName());
        return random.nextInt(100);
    }
    
    private void doSomething() throws InterruptedException {
        TimeUnit.SECONDS.sleep(3);
    }
}
